package mcia_gui;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

/*
 * AdmManageAccounts.java - It is frame that appears when user with 'admin' priviliges push button 'Manage Accounts'.
 * It enables admin to change his password and also to manage managers accounts - add, delete and change theirs password.
 *
 * @author MCIA
 */
public class AdmManageAccounts extends javax.swing.JFrame {

    private DatabaseEss db;                                                     //connection to db
    private String dbName = "mcia";                                             //name of db we are connecting to
    MessageDigest md;                                                           //used to encryption of the password

    public AdmManageAccounts() {
        initComponents();

        db = new DatabaseEss(dbName);

        //setting text in status label
        statusLabel.setText("User: " + LogOn.globalUsername);

        loadUsers();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        ClosingConfirmation = new javax.swing.JFrame();
        jPanel5 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        OK = new javax.swing.JButton();
        Cancel = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        statusLabel = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        backButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        adminUsernameField = new javax.swing.JTextField();
        adminPasswordField = new javax.swing.JPasswordField();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        adminNewPasswordField = new javax.swing.JPasswordField();
        jLabel7 = new javax.swing.JLabel();
        adminRepeatPasswordField = new javax.swing.JPasswordField();
        changeAdminPassButton = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        adminCurrentPasswordField = new javax.swing.JPasswordField();
        jLabel11 = new javax.swing.JLabel();
        userRepeatPasswordField = new javax.swing.JPasswordField();
        updateUserButton = new javax.swing.JButton();
        usersCombo = new javax.swing.JComboBox();
        userNewPasswordField = new javax.swing.JPasswordField();
        jLabel12 = new javax.swing.JLabel();
        deleteUserButton = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();

        ClosingConfirmation.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        ClosingConfirmation.setTitle("Quit Application?");
        ClosingConfirmation.setAlwaysOnTop(true);
        ClosingConfirmation.setBounds(new java.awt.Rectangle(500, 350, 0, 0));
        ClosingConfirmation.setMaximizedBounds(new java.awt.Rectangle(300, 300, 232, 97));
        ClosingConfirmation.setMinimumSize(new java.awt.Dimension(232, 110));
        ClosingConfirmation.setName("closeConfirmation"); // NOI18N
        ClosingConfirmation.setResizable(false);

        jPanel5.setPreferredSize(new java.awt.Dimension(320, 97));

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel5.setText("Do you really want to quit?");

        OK.setText("Quit");
        OK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OKActionPerformed(evt);
            }
        });

        Cancel.setText("Cancel");
        Cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(OK, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(Cancel))
                    .addComponent(jLabel5))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addComponent(jLabel5)
                .addGap(14, 14, 14)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(OK)
                    .addComponent(Cancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout ClosingConfirmationLayout = new javax.swing.GroupLayout(ClosingConfirmation.getContentPane());
        ClosingConfirmation.getContentPane().setLayout(ClosingConfirmationLayout);
        ClosingConfirmationLayout.setHorizontalGroup(
            ClosingConfirmationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ClosingConfirmationLayout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );
        ClosingConfirmationLayout.setVerticalGroup(
            ClosingConfirmationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ClosingConfirmationLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("MCIA LightControl");
        setBounds(new java.awt.Rectangle(200, 20, 800, 600));
        setMaximizedBounds(new java.awt.Rectangle(0, 0, 800, 600));
        setMinimumSize(new java.awt.Dimension(800, 600));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        statusLabel.setText("User: Not Logged In");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
        );

        jPanel3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Manage users accounts");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 784, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
                .addContainerGap())
        );

        backButton.setText("Back");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Change Admin Password", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel3.setText("Username:");

        adminUsernameField.setFont(new java.awt.Font("Tahoma", 0, 14));
        adminUsernameField.setText("admin");
        adminUsernameField.setEnabled(false);
        adminUsernameField.setName(""); // NOI18N
        adminUsernameField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                adminUsernameFieldKeyPressed(evt);
            }
        });

        adminPasswordField.setFont(new java.awt.Font("Tahoma", 0, 14));
        adminPasswordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                adminPasswordFieldKeyPressed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel4.setText("Current Password:");

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel6.setText("Admin New Password:");

        adminNewPasswordField.setFont(new java.awt.Font("Tahoma", 0, 14));
        adminNewPasswordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                adminNewPasswordFieldKeyPressed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel7.setText("Repeat New Password:");

        adminRepeatPasswordField.setFont(new java.awt.Font("Tahoma", 0, 14));
        adminRepeatPasswordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                adminRepeatPasswordFieldKeyPressed(evt);
            }
        });

        changeAdminPassButton.setText("Change Admin Password");
        changeAdminPassButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeAdminPassButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)
                        .addComponent(jLabel6))
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(changeAdminPassButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                    .addComponent(adminRepeatPasswordField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                    .addComponent(adminPasswordField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                    .addComponent(adminUsernameField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                    .addComponent(adminNewPasswordField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE))
                .addGap(29, 29, 29))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(adminUsernameField, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(adminPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(adminNewPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(adminRepeatPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(changeAdminPassButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(69, Short.MAX_VALUE))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Change Other User Password", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel8.setText("Username:");

        jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel10.setText("Admin Password:");

        adminCurrentPasswordField.setFont(new java.awt.Font("Tahoma", 0, 14));
        adminCurrentPasswordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                adminCurrentPasswordFieldKeyPressed(evt);
            }
        });

        jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel11.setText("Repeat New Password:");

        userRepeatPasswordField.setFont(new java.awt.Font("Tahoma", 0, 14));
        userRepeatPasswordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                userRepeatPasswordFieldKeyPressed(evt);
            }
        });

        updateUserButton.setText("Update User");
        updateUserButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateUserButtonActionPerformed(evt);
            }
        });

        usersCombo.setEditable(true);
        usersCombo.setFont(new java.awt.Font("Tahoma", 0, 14));
        usersCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "- No users -" }));

        userNewPasswordField.setFont(new java.awt.Font("Tahoma", 0, 14));
        userNewPasswordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                userNewPasswordFieldKeyPressed(evt);
            }
        });

        jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel12.setText("User New Password:");

        deleteUserButton.setText("Delete This User");
        deleteUserButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteUserButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                        .addGap(80, 80, 80)
                        .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(usersCombo, 0, 198, Short.MAX_VALUE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel4Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel11)
                                    .addComponent(jLabel12)))
                            .addGroup(jPanel4Layout.createSequentialGroup()
                                .addGap(43, 43, 43)
                                .addComponent(jLabel10)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(adminCurrentPasswordField, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE)
                            .addComponent(updateUserButton, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE)
                            .addComponent(userNewPasswordField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE)
                            .addComponent(userRepeatPasswordField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE)
                            .addComponent(deleteUserButton, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(usersCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(adminCurrentPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userNewPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userRepeatPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(updateUserButton, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(deleteUserButton, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(29, Short.MAX_VALUE))
        );

        jLabel2.setText("* To add user simply write new username and admin password, also providing new user password.");

        jLabel9.setText("** To remove user select his username and type admin password, then click 'Delete This User'.");

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel6Layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(13, Short.MAX_VALUE))
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(jLabel2)
                .addGap(4, 4, 4)
                .addComponent(jLabel9)
                .addContainerGap(13, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(16, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
    }//GEN-LAST:event_formKeyPressed

    private void adminPasswordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_adminPasswordFieldKeyPressed
    }//GEN-LAST:event_adminPasswordFieldKeyPressed

    private void OKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKActionPerformed
        //exit program
        this.dispose();
        System.exit(0);
}//GEN-LAST:event_OKActionPerformed

    private void CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelActionPerformed
        // hide closingConfirmation
        ClosingConfirmation.dispose();
}//GEN-LAST:event_CancelActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // show closingConfirmation
        ClosingConfirmation.setVisible(true);
    }//GEN-LAST:event_formWindowClosing

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
        //return to AdmWelcome screen
        AdmWelcome welcomeScreen = new AdmWelcome();
        Main.changeFrame(welcomeScreen);
    }//GEN-LAST:event_backButtonActionPerformed

    private void adminNewPasswordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_adminNewPasswordFieldKeyPressed

    }//GEN-LAST:event_adminNewPasswordFieldKeyPressed

    private void adminRepeatPasswordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_adminRepeatPasswordFieldKeyPressed

    }//GEN-LAST:event_adminRepeatPasswordFieldKeyPressed

    private void adminUsernameFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_adminUsernameFieldKeyPressed

}//GEN-LAST:event_adminUsernameFieldKeyPressed

    private void adminCurrentPasswordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_adminCurrentPasswordFieldKeyPressed

    }//GEN-LAST:event_adminCurrentPasswordFieldKeyPressed

    private void userRepeatPasswordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_userRepeatPasswordFieldKeyPressed

    }//GEN-LAST:event_userRepeatPasswordFieldKeyPressed

    private void changeAdminPassButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeAdminPassButtonActionPerformed
        //changing admin password
        try {
            changeAdminPass();
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AdmManageAccounts.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_changeAdminPassButtonActionPerformed

    private void updateUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateUserButtonActionPerformed
        //update user account
        try {
            updateUser();
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AdmManageAccounts.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_updateUserButtonActionPerformed

    private void userNewPasswordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_userNewPasswordFieldKeyPressed

    }//GEN-LAST:event_userNewPasswordFieldKeyPressed

    private void deleteUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteUserButtonActionPerformed
        try {
            md = MessageDigest.getInstance("SHA1");
            String input = String.valueOf(adminCurrentPasswordField.getPassword());
            md.update(input.getBytes());
            byte[] output = md.digest();
            String currentHashedPass = bytesToHex(output);
            System.out.println("current password hashed: " + currentHashedPass);

            //accessing db and checking admin password
            db.stmt = db.conn.createStatement();
            ResultSet results = db.stmt.executeQuery("SELECT * FROM users WHERE name = 'admin'");
            results.next();

            String adminPassFromDB = results.getString("PASSWORD");
            System.out.println("Pass from DB: " + adminPassFromDB);
            results.close();

            if (adminPassFromDB.equals(currentHashedPass)) {
                try {
                    //deleting user
                    db.stmt = db.conn.createStatement();
                    String userName = usersCombo.getSelectedItem().toString();
                    String truncate_query = "DELETE FROM users WHERE name = '" + userName + "'";
                    int results0 = db.stmt.executeUpdate(truncate_query);
                    if (results0 == 0) {
                        System.out.println("ERROR: User not deleted!");
                        JOptionPane.showMessageDialog(this, "ERROR DELETING USER: User not deleted!", "User is not deleted.", JOptionPane.ERROR_MESSAGE);
                    } else {
                        System.out.println("User deleted.");
                        JOptionPane.showMessageDialog(this, "User has been deleted!", "User has been deleted.", JOptionPane.INFORMATION_MESSAGE);
                        loadUsers();
                    }
                    db.stmt.close();
                } catch (SQLException ex) {
                    Logger.getLogger(AdmManageAccounts.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                //admin pass not correct
                JOptionPane.showMessageDialog(this, "Admin current password incorrect!", "Admin password is not correct.", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            Logger.getLogger(AdmManageAccounts.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AdmManageAccounts.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_deleteUserButtonActionPerformed

    private void loadUsers() {
        //loading usernames for combo list
        try {
            //accessing db
            db.stmt = db.conn.createStatement();
            ResultSet results = db.stmt.executeQuery("SELECT * FROM users WHERE name <> 'admin'");

            usersCombo.removeAllItems();
            while (results.next()) {

                String name = results.getString("NAME");
                usersCombo.addItem(name);
            }
            results.close();

            if (usersCombo.getItemCount() == 0) {
                usersCombo.addItem("- No users -");
            }
        } catch (SQLException ex) {
            Logger.getLogger(AdmManageAccounts.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void updateUser() throws NoSuchAlgorithmException {
        //setting new password for user
        md = MessageDigest.getInstance("SHA1");
        String input = String.valueOf(adminCurrentPasswordField.getPassword());
        md.update(input.getBytes());
        byte[] output = md.digest();
        String currentHashedPass = bytesToHex(output);
        System.out.println("current password hashed: " + currentHashedPass);

        try {
            //accessing db and checking admin password
            db.stmt = db.conn.createStatement();
            ResultSet results = db.stmt.executeQuery("SELECT * FROM users WHERE name = 'admin'");
            results.next();

            String adminPassFromDB = results.getString("PASSWORD");
            System.out.println("Pass from DB: " + adminPassFromDB);
            results.close();

            if (adminPassFromDB.equals(currentHashedPass)) {
                char[] newPass1 = userNewPasswordField.getPassword();
                char[] newPass2 = userRepeatPasswordField.getPassword();

                int created = 0;

                //check if there is such username in database (if not - create one)
                db.stmt = db.conn.createStatement();
                String newUserName = usersCombo.getSelectedItem().toString();
                System.out.println("user: " + newUserName);
                ResultSet results_check = db.stmt.executeQuery("SELECT * FROM users WHERE name = '" + newUserName + "'");
                if (results_check.next()) {
                    //exists
                } else {
                    //not exists
                    System.out.println("User not exists. Making new.");

                    db.stmt = db.conn.createStatement();

                    String tmpPass = "tmpPass";

                    String query = "INSERT INTO users (NAME, PASSWORD) VALUES ('" + newUserName + "', '" + tmpPass + "')";
                    System.out.println(query);
                    int results_insert = db.stmt.executeUpdate(query);

                    if (results_insert == 0) {
                        System.out.println("User not added to db!");
                        return;
                    } else {
                        System.out.println("Unit inserted into db: " + newUserName);
                        created = 1;
                    }

                    db.stmt.close();
                }
                results_check.close();

                if (Arrays.equals(newPass1, newPass2) && userNewPasswordField.getPassword().length > 0) {
                    //everything correct - we change pass in database
                    //inserting record
                    db.stmt = db.conn.createStatement();

                    String input2 = String.valueOf(userNewPasswordField.getPassword());
                    md.update(input2.getBytes());
                    byte[] output2 = md.digest();
                    String newHashedPass = bytesToHex(output2);
                    String query = "UPDATE users SET PASSWORD = '" + newHashedPass + "' WHERE name = '" + newUserName + "'";
                    System.out.println(query);
                    int results2 = db.stmt.executeUpdate(query);

                    if (results2 == 0) {
                        System.out.println("Record not changed!");
                        JOptionPane.showMessageDialog(this, "ERROR CHANGING PASSWORD: New password not changed!", "User new password is not changed.", JOptionPane.ERROR_MESSAGE);
                        return;
                    } else {
                        System.out.println("User password inserted into db.");
                    }

                    db.stmt.close();
                    input2 = "---";

                    if (created == 0) {
                        JOptionPane.showMessageDialog(this, "New password for user has been set!", "User new password is changed.", JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(this, "New user has been created!", "User created.", JOptionPane.INFORMATION_MESSAGE);
                    }
                    return;
                } else if (userNewPasswordField.getPassword().length == 0) {
                    JOptionPane.showMessageDialog(this, "New password cannot be empty!", "User new password is not correct.", JOptionPane.ERROR_MESSAGE);
                    return;
                } else {
                    JOptionPane.showMessageDialog(this, "New password is not the same with one repeated!", "User new password is not correct.", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } else {
                JOptionPane.showMessageDialog(this, "Admin current password incorrect!", "Admin password is not correct.", JOptionPane.ERROR_MESSAGE);
                return;
            }

        } catch (SQLException ex) {
            Logger.getLogger(AdmManageAccounts.class.getName()).log(Level.SEVERE, null, ex);
        }
        input = "---";
    }

    private void changeAdminPass() throws NoSuchAlgorithmException {
        md = MessageDigest.getInstance("SHA1");
        String input = String.valueOf(adminPasswordField.getPassword());
        md.update(input.getBytes());
        byte[] output = md.digest();
        String currentHashedPass = bytesToHex(output);
        System.out.println("current password hashed: " + currentHashedPass);

        try {
            //accessing db
            db.stmt = db.conn.createStatement();
            ResultSet results = db.stmt.executeQuery("SELECT * FROM users WHERE name = 'admin'");
            results.next();

            String passFromDB = results.getString("PASSWORD");
            System.out.println("Pass from DB: " + passFromDB);
            results.close();

            if (passFromDB.equals(currentHashedPass)) {
                System.out.println("Password is correct with this in database.");

                char[] newPass1 = adminNewPasswordField.getPassword();
                char[] newPass2 = adminRepeatPasswordField.getPassword();
                if (Arrays.equals(newPass1, newPass2) && adminNewPasswordField.getPassword().length > 0) {
                    //everything correct - we change pass in database
                    //inserting record
                    db.stmt = db.conn.createStatement();

                    String input2 = String.valueOf(adminNewPasswordField.getPassword());
                    md.update(input2.getBytes());
                    byte[] output2 = md.digest();
                    String newHashedPass = bytesToHex(output2);
                    String query = "UPDATE users SET PASSWORD = '" + newHashedPass + "' WHERE name = 'admin'";
                    System.out.println(query);
                    int results2 = db.stmt.executeUpdate(query);

                    if (results2 == 0) {
                        System.out.println("Record not changed!");
                        JOptionPane.showMessageDialog(this, "ERROR CHANGING PASSWORD: New password not changed!", "Admin new password is not changed.", JOptionPane.ERROR_MESSAGE);
                        return;
                    } else {
                        System.out.println("User password inserted into db.");
                    }

                    db.stmt.close();
                    input2 = "---";

                    JOptionPane.showMessageDialog(this, "New Admin password has been set!", "Admin new password is changed.", JOptionPane.INFORMATION_MESSAGE);
                    return;
                } else if (adminNewPasswordField.getPassword().length == 0) {
                    JOptionPane.showMessageDialog(this, "New password cannot be empty!", "Admin new password is not correct.", JOptionPane.ERROR_MESSAGE);
                    return;
                } else {
                    JOptionPane.showMessageDialog(this, "New password is not the same with one repeated!", "Admin new password is not correct.", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } else {
                JOptionPane.showMessageDialog(this, "Admin current password incorrect!", "Admin password is not correct.", JOptionPane.ERROR_MESSAGE);
                return;
            }

        } catch (SQLException ex) {
            Logger.getLogger(AdmManageAccounts.class.getName()).log(Level.SEVERE, null, ex);
        }
        input = "---";
    }

    public static String bytesToHex(byte[] b) {
        //change bytes to hexadecimal values
        char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        StringBuilder buf = new StringBuilder();
        for (int j = 0; j < b.length; j++) {
            buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
            buf.append(hexDigit[b[j] & 0x0f]);
        }
        return buf.toString();
    }

    public static void main(String args[]) {
        //setting Windows Look and Feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println("Error setting native LAF: " + ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    AdmManageAccounts thisFrame = new AdmManageAccounts();
                    String[] vars = null;
                    Main.main(vars);
                    Main.changeFrame(thisFrame);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(AdmWelcome.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(AdmWelcome.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Cancel;
    private javax.swing.JFrame ClosingConfirmation;
    private javax.swing.JButton OK;
    private javax.swing.JPasswordField adminCurrentPasswordField;
    private javax.swing.JPasswordField adminNewPasswordField;
    private javax.swing.JPasswordField adminPasswordField;
    private javax.swing.JPasswordField adminRepeatPasswordField;
    private javax.swing.JTextField adminUsernameField;
    private javax.swing.JButton backButton;
    private javax.swing.JButton changeAdminPassButton;
    private javax.swing.JButton deleteUserButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JLabel statusLabel;
    private javax.swing.JButton updateUserButton;
    private javax.swing.JPasswordField userNewPasswordField;
    private javax.swing.JPasswordField userRepeatPasswordField;
    private javax.swing.JComboBox usersCombo;
    // End of variables declaration//GEN-END:variables
}
